#include <iostream>
#include <unistd.h>
#include <string>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <cstring>
#include <arpa/inet.h>
#include "Thread.hpp"
#include "InetAddr.hpp"

void RecverMessage(int sockfd, const std::string &name)
{
    while (1)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        char message[1024];
        int n = recvfrom(sockfd, message, sizeof(message) - 1, 0, (struct sockaddr *)&peer, &len);
        if (n > 0)
        {
            std::cout << message << std::endl;
        }
    }
}

void SendMessage(int sockfd, const std::string server_ip, uint16_t port, const std::string &name)
{
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    while (1)
    {
        std::string message;
        std::cout << "Please Enter# ";
        std::cin >> message;

        int n = ::sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            std::cout << "sendto error" << std::endl;
            exit(1);
        }
    }
}

int main(int argc, char *args[])
{
    if (argc != 3)
    {
        std::cout << "./UdpClient serverip serverport" << std::endl;
        exit(0);
    }
    std::string server_ip = args[1];
    uint16_t port = std::stoi(args[2]);
    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);

    Thread Rcvm("recver-thread", std::bind(&RecverMessage, sockfd, std::placeholders::_1));
    Thread Send("Sent-thread", std::bind(&SendMessage, sockfd, server_ip, port, std::placeholders::_1));

    Rcvm.start();
    Send.start();

    Rcvm.join();
    Send.join();

    ::close(sockfd);

    // while (1)
    // {
    //     std::string line;
    //     std::cout << "Please Enter# ";
    //     std::getline(std::cin, line);

    //     int n = sendto(sockfd, line.c_str(), line.size(), 0, (struct sockaddr *)&server, sizeof(server));
    //     if (n > 0)
    //     {
    //         struct sockaddr_in temp;
    //         char buffer[1024];
    //         socklen_t len = sizeof(temp);
    //         int m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
    //         if (m > 0)
    //         {
    //             buffer[m] = 0;
    //             std::cout << buffer << std::endl;
    //         }
    //         else
    //         {
    //             std::cout << "recvfrom error" << std::endl;
    //             break;
    //         }
    //     }
    //     else
    //     {
    //         std::cout<<"sendto error"<<std::endl;
    //         break;
    //     }
    // }
    // ::close(sockfd);

    return 0;
}